package com.saftalk;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.saftalk.db.PMF;
import com.saftalk.db.entity.User;
import com.saftalk.ui.UIMessageResult;
import com.saftalk.ui.UIPresenceListResult;
import com.saftalk.ui.UIPresenceResult;
import com.saftalk.ui.UIUserResult;

public class PresenceServlet  extends BaseServlet{
	
	
	private static final long serialVersionUID = 5740391749693905177L;
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain; charset=UTF-8");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		
		Object sessionInfo = req.getSession().getAttribute("user");
		if (sessionInfo == null){
			gson.toJson(new UIMessageResult(false, "User is not logged in"),resp.getWriter());
			return;
		}
		
		UIUserResult user = (UIUserResult)sessionInfo;
		
		UIPresenceListResult list = (UIPresenceListResult) cache.get(user.getFamilyId());
		if (list == null) {
			list = new UIPresenceListResult();
			
			Query q = pm.newQuery(User.class);
			List<User> queryResults = null;
			try {
				q.setFilter("familyId == familyIdParam");
				q.declareParameters("Long familyIdParam");
				queryResults = (List<User>) q.execute(user.getFamilyId());	
			} catch (Exception e) {
				e.printStackTrace();
				gson.toJson(new UIMessageResult(false, "Failed to get users"),
						resp.getWriter());
			} finally {
				q.closeAll();
			}
			for (User u : queryResults) {
				UIPresenceResult pres = new UIPresenceResult(u);
				list.addOrSet(pres);
			}
		}
		
		UIPresenceResult userPresence = list.get(user.getUserId());
		if (userPresence == null) {
			userPresence =  new UIPresenceResult(user);
			list.addOrSet(userPresence);
		}
		
		for (UIPresenceResult pres : list.list()) {
			if (user.getUserId().equals(pres.getUserId())) {
				pres.see();
			} else {
				if (pres.getLastSeen() < (new Date().getTime() - 10000)) {
					pres.offline();
				}
			}
		}
		cache.put(user.getFamilyId(), list);
		list.fillResults();
		gson.toJson(list, resp.getWriter());
			
		
	}
	
}
